{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# How to discretize a integral filter with Tustin's method\n",
    "First a continous time filter is constructed. This filter will be discretized with Tustin's method and converted into C++ code."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sympy import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "s, T, z = symbols('s,T,z')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First our continous time system"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "sys = 1 / s"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translate to discrete"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/latex": [
       "$\\displaystyle \\frac{T \\left(z + 1\\right)}{2 \\left(z - 1\\right)}$"
      ],
      "text/plain": [
       "T*(z + 1)/(2*(z - 1))"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sys = sys.subs(s, 2 / T * (z - 1) / (z + 1))\n",
    "sys"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translate that to C++"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "H = y/u = T / 2 * (z + 1)/(z - 1)\n",
    "\n",
    "u * T / 2 * (z + 1) = y * (z - 1)\n",
    "u * T / 2 * (1 + z^-1) = y * (1 - z^-1)\n",
    "T / 2 * (u[0] + u[1]) = y[0] - y[1]\n",
    "y[0] = T / 2 * (u[0] + u[1]) + y[1]\n",
    "```\n",
    "\n",
    "```c++\n",
    "y[0] = T / 2 * (u[0] + u[1]) + y[1]\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
